//
//  LookServiceViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/5/10.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
class LookServiceViewController: BaseViewController {

    @IBOutlet var planTableview: UITableView!
    @IBOutlet var taskTypeLabel: UILabel!
    @IBOutlet var userNameLabel: UILabel!
    @IBOutlet var priceLabel: UILabel!
    
    @IBOutlet var contentLabel: UILabel!
    
    @IBOutlet var userHeaderImageView: UIImageView!
    
    @IBOutlet var phoneLabel: UILabel!
    
    @IBOutlet var appointMentTimeLabel: UILabel!
    
    @IBOutlet var carNumLabel: UILabel!
    
    
    @IBOutlet var carModelLabel: UILabel!
    
    @IBOutlet var carMileageLabel: UILabel!
    
    
    @IBOutlet var locationBtn: UIButton!
    
    
    var taskModel:PlatformTaskModel?
    
    var planModels:[PlanModel]?
    
    var currentPage = 1
    
    var totalPage = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        updateVcEvents()
        configView()
        requstPlanList(page: currentPage, taskId: (taskModel?.tid)!)
    }
    
    func configView() -> Void {
        planTableview.delegate = self
        planTableview.dataSource = self
        planTableview.separatorStyle = .none
        planTableview.showsVerticalScrollIndicator = false
        planTableview.register(UINib(nibName: "LookServiceTableViewCell", bundle: nil), forCellReuseIdentifier: "lookservicetaskCell")
    }
    
    
    func updateVcEvents() -> Void {
        
        userHeaderImageView.roundCorner(radius: userHeaderImageView.frame.height/2)
        taskTypeLabel.roundCorner(radius: 3)
        taskTypeLabel.layer.borderWidth = 1
        taskTypeLabel.layer.borderColor = UIColor.HexColor(0x727272).cgColor
        priceLabel.text = "预算:¥" + (taskModel?.budget_money)! + "元"
        userHeaderImageView.sd_setImage(with: (NSURL(string:(taskModel?.shead_url)!)! as URL), placeholderImage: UIImage.init(named: "defultHeaderImg"))
        contentLabel.text = "备注:" + (taskModel?.describe)!
        userNameLabel.text = taskModel?.sname
        taskTypeLabel.text = taskModel?.name
        phoneLabel.text = "电话:" + replaceStrForPhone(str: (taskModel?.phone)!)        
        appointMentTimeLabel.text = "预约时间:" + (taskModel?.subscribe_time)!
        carNumLabel.text = "车牌号:" + (taskModel?.num)!
        carModelLabel.text = "车型:" + (taskModel?.car_model)!
        carMileageLabel.text = "行驶里程:" + (taskModel?.mileage)! + "KM"
        locationBtn.setTitle(taskModel?.address, for: UIControlState.normal)
    }
    
    
    
    @IBAction func changeBatchBtnPress(_ sender: UIButton) {
        if totalPage > 0 {
            if self.totalPage > currentPage {
                currentPage += 1
                self.requstPlanList(page: currentPage, taskId: (taskModel?.tid)!)
            }else {
                currentPage = 1
                self.requstPlanList(page: currentPage, taskId: (taskModel?.tid)!)
            }
            
        }
    }
    
    
    
    //网络请求
    //获取需求下的方案列表
    func requstPlanList(page:Int,taskId:String) -> Void {
        
        Alamofire.request(getPlanListUrl, method:.post, parameters: ["page": page,"id":taskId,"uid":UserModel.shareUser.data?.uid ?? String()])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<PlanModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        if (basemodel.data?.data?.count)! > 0 {
                            
                            self.planModels = basemodel.data?.data
                            self.totalPage = (basemodel.data?.last_page)!
                            self.planTableview.reloadData()
                        }
//                        if page == 1 {
//                            self.planModels?.removeAll()
//                            self.planModels = basemodel.data?.data
//                        }else {
//                            if ((basemodel.data?.data?.count)! > 0) {
//                                self.planModels! += (basemodel.data?.data)!
//                            }else {
//                                return
//                            }
//                        }
                        
                    case false:
                        MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                case false:
                    print(response.result.error!)
                }
                
                
        }
    }
    
    
    
    @IBAction func lookLocationBtnPress(_ sender: UIButton) {
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

extension LookServiceViewController: UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.planModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "lookservicetaskCell", for: indexPath) as! LookServiceTableViewCell
        cell.selectionStyle = .none
        let model = planModels![indexPath.row]
        cell.contentLabel.text = "方案:" + model.plan
        //除了自己的报价 其他的显示**** 需求：商家之间屏蔽报价
        if model.uid == UserModel.shareUser.data?.uid {
            cell.priceLabel.text = "报价:¥" + model.offer
        }else {
            cell.priceLabel.text = "报价:¥****"
        }
        
        cell.userHeaderImageView.sd_setImage(with: (NSURL(string:(model.member?.thumb)!)! as URL), placeholderImage: UIImage.init(named: "defultHeaderImg"))
        cell.userNameLabel.text = model.member?.name
        //判断是否显示签约状态
        if taskModel?.status == "0" {//=====已发布
            cell.signStatusLabel.isHidden = true
        }else {//=====已完成 已关闭
            cell.signStatusLabel.isHidden = false
            if model.status == "0" {//0 方案签约失败
                cell.signStatusLabel.text = "签约失败"
                cell.signStatusLabel.textColor = UIColor.HexColor(0x727272)
            }else {//1 方案签约成功
                cell.signStatusLabel.text = "签约成功"
                cell.signStatusLabel.textColor = BaseColor.NavColor
            }
        }
        cell.cellUserheaderbtnblock {
            if model.member?.id != "" {
                let storeDetailsVC = BaseWebViewController()
                storeDetailsVC.title = "袋鼠好车商户详情";
                storeDetailsVC.loadUrl = merchantDetailsWebUrl + "/id/" + (model.member?.id)!
                self.navigationController?.pushViewController(storeDetailsVC, animated: true)
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return ScaleHeight(120)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
}
